package com.example.managemyself.ui.tasks;

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.example.managemyself.R;
import com.example.managemyself.data.model.Task;
import com.example.managemyself.viewmodel.TaskViewModel;

import java.util.Date;

public class AddEditTaskActivity extends AppCompatActivity {
    
    public static final String EXTRA_TASK_ID = "task_id";
    public static final String EXTRA_TASK_TYPE = "task_type";
    
    private EditText etTitle;
    private EditText etDescription;
    private Spinner spinnerType;
    private SeekBar seekBarImportance;
    private SeekBar seekBarUrgency;
    private TextView tvImportanceValue;
    private TextView tvUrgencyValue;
    private Button btnSave;
    private Button btnCancel;
    
    private TaskViewModel taskViewModel;
    private Task currentTask;
    private boolean isEditMode = false;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_edit_task);
        
        // 设置ActionBar
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        
        initViews();
        setupViewModel();
        setupSpinners();
        setupSeekBars();
        setupButtons();
        
        // 检查是否是编辑模式
        int taskId = getIntent().getIntExtra(EXTRA_TASK_ID, -1);
        if (taskId != -1) {
            isEditMode = true;
            setTitle(getString(R.string.edit_task));
            loadTask(taskId);
        } else {
            setTitle(getString(R.string.add_task));
            // 从Intent获取任务类型
            String taskType = getIntent().getStringExtra(EXTRA_TASK_TYPE);
            if (taskType != null) {
                setTaskTypeSelection(taskType);
            }
        }
    }
    
    private void initViews() {
        etTitle = findViewById(R.id.etTitle);
        etDescription = findViewById(R.id.etDescription);
        spinnerType = findViewById(R.id.spinnerType);
        seekBarImportance = findViewById(R.id.seekBarImportance);
        seekBarUrgency = findViewById(R.id.seekBarUrgency);
        tvImportanceValue = findViewById(R.id.tvImportanceValue);
        tvUrgencyValue = findViewById(R.id.tvUrgencyValue);
        btnSave = findViewById(R.id.btnSave);
        btnCancel = findViewById(R.id.btnCancel);
    }
    
    private void setupViewModel() {
        taskViewModel = new ViewModelProvider(this).get(TaskViewModel.class);
    }
    
    private void setupSpinners() {
        // 设置任务类型下拉框
        String[] taskTypes = {"学习", "健康", "杂务", "工作", "娱乐"};
        ArrayAdapter<String> typeAdapter = new ArrayAdapter<>(this, 
            android.R.layout.simple_spinner_item, taskTypes);
        typeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerType.setAdapter(typeAdapter);
    }
    
    private void setupSeekBars() {
        // 设置重要程度滑块
        seekBarImportance.setMax(10);
        seekBarImportance.setProgress(5);
        tvImportanceValue.setText("5");
        
        seekBarImportance.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tvImportanceValue.setText(String.valueOf(progress));
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
        
        // 设置紧急程度滑块
        seekBarUrgency.setMax(10);
        seekBarUrgency.setProgress(5);
        tvUrgencyValue.setText("5");
        
        seekBarUrgency.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                tvUrgencyValue.setText(String.valueOf(progress));
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }
    
    private void setupButtons() {
        btnSave.setOnClickListener(v -> saveTask());
        btnCancel.setOnClickListener(v -> finish());
    }
    
    private void setTaskTypeSelection(String taskType) {
        ArrayAdapter<String> adapter = (ArrayAdapter<String>) spinnerType.getAdapter();
        int position = adapter.getPosition(taskType);
        if (position >= 0) {
            spinnerType.setSelection(position);
        }
    }
    
    private void loadTask(int taskId) {
        taskViewModel.getTaskById(taskId).observe(this, task -> {
            if (task != null) {
                currentTask = task;
                populateFields(task);
            }
        });
    }
    
    private void populateFields(Task task) {
        etTitle.setText(task.getTitle());
        etDescription.setText(task.getDescription());
        
        if (task.getType() != null) {
            setTaskTypeSelection(task.getType());
        }
        
        seekBarImportance.setProgress(task.getImportance());
        
        // 处理紧急程度
        String urgency = task.getUrgency();
        if (urgency != null) {
            try {
                int urgencyValue = Integer.parseInt(urgency);
                seekBarUrgency.setProgress(urgencyValue);
            } catch (NumberFormatException e) {
                seekBarUrgency.setProgress(5); // 默认值
            }
        }
    }
    
    private void saveTask() {
        String title = etTitle.getText().toString().trim();
        String description = etDescription.getText().toString().trim();
        
        if (title.isEmpty()) {
            Toast.makeText(this, "请输入任务标题", Toast.LENGTH_SHORT).show();
            return;
        }
        
        String type = spinnerType.getSelectedItem().toString();
        int importance = seekBarImportance.getProgress();
        String urgency = String.valueOf(seekBarUrgency.getProgress());
        
        if (isEditMode && currentTask != null) {
            // 更新现有任务
            currentTask.setTitle(title);
            currentTask.setDescription(description);
            currentTask.setType(type);
            currentTask.setImportance(importance);
            currentTask.setUrgency(urgency);
            
            taskViewModel.updateTask(currentTask);
            Toast.makeText(this, "任务已更新", Toast.LENGTH_SHORT).show();
        } else {
            // 创建新任务
            Task newTask = new Task(title, description);
            newTask.setType(type);
            newTask.setImportance(importance);
            newTask.setUrgency(urgency);
            newTask.setCreatedDate(new Date());
            
            taskViewModel.insertTask(newTask);
            Toast.makeText(this, "任务已添加", Toast.LENGTH_SHORT).show();
        }
        
        finish();
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
